package apiv1

import (
	"go-mp-starter/app/common/request"
	"go-mp-starter/app/common/response"
	"go-mp-starter/app/services"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

// Login 用户登陆操作
// @method POST
func Login(ctx *gin.Context) {
	var form request.Login
	if err := ctx.ShouldBindJSON(&form); err != nil {
		response.ValidateFail(ctx, request.GetErrorMsg(form, err))
		return
	}

	if user, err := services.UserService.Login(form); err != nil {
		response.BusinessFail(ctx, err.Error())
		return
	} else {
		// 由user获取对应token
		tokenData, _, err := services.JwtService.CreateToken(services.AppGuardName, user)
		if err != nil {
			response.BusinessFail(ctx, err.Error())
			return
		}
		response.Success(ctx, tokenData)
	}
}

// Refresh 刷新token
func Refresh(ctx *gin.Context) {
	var id = ctx.Keys["id"].(string)
	var oldToken = ctx.Keys["token"].(*jwt.Token)
	user, err := services.UserService.GetUserInfo(id)
	if err != nil {
		response.BusinessFail(ctx, err.Error())
		return
	}
	token, _, err := services.JwtService.CreateToken(services.AppGuardName, user)

	if err != nil {
		response.BusinessFail(ctx, err.Error())
		return
	}
	//将旧的jwt token加入黑名单
	_ = services.JwtService.JoinBlackList(oldToken)

	response.Success(ctx, token)
}

// Logout 用户登出
// @method POST
func Logout(ctx *gin.Context) {
	// 将jwt token加入黑名单
	token := ctx.Keys["token"].(*jwt.Token)
	if err := services.JwtService.JoinBlackList(token); err != nil {
		response.BusinessFail(ctx, "登出失败")
		return
	}
	response.Success(ctx, nil)
}
